

import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;

 

public class TablePanel extends JPanel {
	
	Model model;
	Color green = new Color(0.0f, 0.5f, 0.0f);
	Color red = new Color(0.5f, 0.0f, 0.0f);
	Color blue = new Color(0.0f, 0.0f, 0.5f);
	
	public TablePanel(Model parent) {
		this.setBackground(green);
		model = parent;
		CardView.setModel(model);
		MIL mil = new MIL();
		this.addMouseListener(mil);
		this.addMouseMotionListener(mil);
	}
	
	public void paintComponent(Graphics g) {
		super.paintComponent(g);
		Graphics2D g2d = (Graphics2D)g;
		
		ArrayList<Card> cards = new ArrayList<Card>();
		Card[] pcs = model.getRoom().getTable().getDeck().getDeck();
		// sort by z
		for (Card card: pcs) {
			if (card==null) {
				System.out.println("NULL");
			} else {
				cards.add(card);
			}
		}
		Collections.sort(cards, new ZComparator());
		for (Card card: cards) {
			CardView.draw(g2d, card, this);
		}
		
	}
	
	public void setModel(Model m) {
		model = m;
	}
	
	public class MIL extends MouseInputAdapter {
		public void mousePressed(MouseEvent e) {
			Card selectedCard = null;
			int z = -1;
			Point p = e.getPoint(); //point of click
			
			Card[] cards = ((Deck)model.getRoom().getTable().getDeck()).getDeck();
			
			for(Card card: cards){
				if(card.getRectangle().contains(p)){//intersects with point
					if(card.getZ() > z){//check if highest z
						z = card.getZ();//set c and z
						selectedCard = card;
					}
				}
			}
			model.selectSingleCard(selectedCard);
			
			model.dragStart(e.getPoint());
		}
		public void mouseDragged(MouseEvent e) {
			model.dragContinue(e.getPoint());
		}
		public void mouseReleased(MouseEvent e) {
			model.dragEnd(e.getPoint());
		}
	}
	
	private class ZComparator implements Comparator<Card> {
		public int compare(Card c1, Card c2) {
			int z1 = c1.getZ();
			int z2 = c2.getZ();
			return z1-z2;
		}
		public boolean equals(Object o) {
			return false;
		}
	}
	
	public void changeBackgroundColour(String colour) {
		if(colour.equals("green")) {
			this.setBackground(green);
		}
		else if(colour.equals("red")) {
			this.setBackground(red);
		} else if(colour.equals("blue")) {
			this.setBackground(blue);
		}
	}
}



